package com.rzjm.exercise.module.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rzjm.exercise.common.base.controller.BaseController;
import com.rzjm.exercise.common.base.data.DataTableLayUI;
import com.rzjm.exercise.common.constant.Constant;
import com.rzjm.exercise.common.log.annotation.Log;
import com.rzjm.exercise.common.utils.*;
import com.rzjm.exercise.module.domain.*;
import com.rzjm.exercise.module.service.*;
import com.rzjm.exercise.sys.core.dict.domain.DictDO;
import com.rzjm.exercise.sys.core.dict.service.DictService;
import com.rzjm.exercise.sys.system.user.domain.UserDO;
import com.rzjm.exercise.sys.system.user.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * 处理记录
 *
 * @author mr.zhou
 * @email zhouwei_nice@163.com
 * @date 2020-12-15 22:36:23
 */

@Controller
@RequestMapping("/module/terminal/record")
public class TerminalCheckRecordController extends BaseController {
    @Resource
    private CkTerminalService ckTerminalService;
    @Resource
    private TerminalFittingService terminalFittingService;
    @Resource
    private ShopService shopService;
    @Resource
    private TerminalCheckRecordService terminalCheckRecordService;
    @Resource
    private TerminalCheckRecordImgService terminalCheckRecordImgService;
    @Resource
    private TerminalRecordRepairService terminalRecordRepairService;
    @Resource
    private WxUserService wxUserService;
    @Resource
    private DictService dictService;
    @Resource
    private UserService userService;

    @Value("${projecturl.imgurl}")
    private String imgUrl;

    @Value("${projecturl.exportPath}")
    private String exportPath;

    @Log("查询处理记录页面")
    @GetMapping("/{isClean}")
    @RequiresPermissions("module:terminal:record")
    String TerminalRecord(Model model, @PathVariable("isClean") Integer isClean) {
        model.addAttribute("isClean",isClean);
        model.addAttribute("isBack",0);
        List<DictDO> dictDOS = dictService.selectListByColumn("type","check-state");
        model.addAttribute("dicts",dictDOS);
        UserDO user = getUser();
        List<Shop> shops = new ArrayList<>();
        if(user.getUserType() == 0 || user.getUserType() == 1){//平台管理员可以查看所有的
            shops = shopService.selectAllList();
        } else if(user.getUserType() == 2 ){//集团管理员可以查看自己所管辖的
            Map<String,Object> map = new HashMap<>();
            map.put("jituan_user_id",user.getUserId());
            shops = shopService.getPageByUserId(map);
        } else if(user.getUserType() == 3){//片区管理员可以查看自己所管辖的
            Map<String,Object> map = new HashMap<>();
            map.put("sys_user_id",user.getUserId());
            shops = shopService.getPageByUserId(map);
        } else if(user.getUserType() == 4 || user.getUserType() == 5 || user.getUserType() == 6){//分厂和巡检人员只能查看自己绑定的那个一个
            Map<String,Object> map = new HashMap<>();
            map.put("id",user.getShopId());
            shops = shopService.getPageByUserId(map);
        }
        model.addAttribute("shops", shops);
        model.addAttribute("userType",user.getUserType());
//        if(isClean == 2){
//            return "module/terminal/health/health";
//        }else{
//            return "module/terminal/record/record";
//        }
        return "module/terminal/record/record";
    }

    @Log("查询处理记录页面")
    @GetMapping("/terminal/{terminalId}")
    @RequiresPermissions("module:terminal:record")
    String TerminalRecord1(Model model,@PathVariable("terminalId") Integer terminalId) {
        model.addAttribute("terminalId",terminalId);
        model.addAttribute("isBack",1);
        CkTerminal terminal = ckTerminalService.findById(terminalId);
        if(terminal!=null){
            model.addAttribute("shopId",terminal.getShopId());
        }
        List<DictDO> dictDOS = dictService.selectListByColumn("type","check-state");
        model.addAttribute("dicts",dictDOS);
        return "module/terminal/record/record";
    }

    @Log("查询处理记录")
    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("module:terminal:record")
    public DataTableLayUI<TerminalCheckRecord> list(DataTableLayUI<TerminalCheckRecord> condition) {
        Map<String,Object> map = condition.getSearchParams();
        String isClean = map.containsKey("search_eq_isClean") ? map.get("search_eq_isClean").toString(): null;
        String checkState = map.containsKey("search_eq_checkState") ? map.get("search_eq_checkState").toString(): null;
        String terminalId = StrUtil.isNotEmpty(map.get("search_eq_terminalId").toString()) ? map.get("search_eq_terminalId").toString():null;
        String begin_time = map.containsKey("search_ge_createTime") ? map.get("search_ge_createTime").toString():null;
        String end_time = map.containsKey("search_le_createTime") ? map.get("search_le_createTime").toString():null;
        String shopId = map.containsKey("search_eq_shopId") ? map.get("search_eq_shopId").toString():null;
        UserDO user = getUser();
        DataTableLayUI<TerminalCheckRecord> dt = null;
        Map<String,Object> map1 = new HashMap<>();
        if(user.getUserType() == 0 || user.getUserType() == 1){
            if(StrUtil.isNotEmpty(shopId)){
                map1.put("shop_id",Integer.parseInt(shopId));
            }
        } else if(user.getUserType() == 2){//集团管理员
            if(StrUtil.isNotEmpty(shopId)){
                map1.put("shop_id",Integer.parseInt(shopId));
            }else{
                map1.put("jituan_user_id",user.getUserId());
            }
        }else if(user.getUserType() == 3){//片区管理员
            if(StrUtil.isNotEmpty(shopId)){
                map1.put("shop_id",Integer.parseInt(shopId));
            }else{
                map1.put("sys_user_id",user.getUserId());
            }
        } else if(user.getUserType() == 4 || user.getUserType() == 5 || user.getUserType() == 6){//巡检人员  分厂管理人员
            if(terminalId == null){//从外面总菜单里查看所有的自己的企业的操作记录
                map1.put("shop_id",user.getShopId());
            }else{
                map1.put("shop_id",Integer.parseInt(shopId));
            }
        }

        CkTerminal ckTerminal = null;
        if(terminalId!=null && !terminalId.equals("")){
            ckTerminal = ckTerminalService.getById(Integer.parseInt(terminalId));
        }
        if(ckTerminal != null){
            map1.put("is_clean",ckTerminal.getIsClean());
        }else{
            map1.put("is_clean",0);
            if(isClean!=null && !isClean.equals("")){
                map1.put("is_clean",Integer.parseInt(isClean));
            }
        }
        if(StrUtil.isNotEmpty(checkState)){
            map1.put("check_state",Integer.parseInt(checkState));
        }
        if(begin_time!=null && end_time!=null){
            map1.put("begin_time",begin_time);
            map1.put("end_time",end_time);
        }
        Page<TerminalCheckRecord> page = terminalCheckRecordService.getPage(condition);
        List<TerminalCheckRecord> list = terminalCheckRecordService.getPageByUserId(page,map1);
        if(list != null){
            list.forEach(record ->{
                Shop shop = shopService.findById(record.getShopId());
                if(shop!=null){
                    record.setShopName(shop.getShopName());
                }
                WxUser wxUser = wxUserService.getById(record.getWxUserId());
                if(wxUser !=null && wxUser.getNickName()!=null){
                    UserDO userDO = userService.findById(wxUser.getSysUserId());
                    if(userDO!=null){
                        record.setUserName(userDO.getName());
                    }
                }

                if(StrUtil.isNotEmpty(record.getSendMsgOkIds())){
                    String names = getWxUserNames(record.getSendMsgOkIds());
                    record.setSendMsgOkIds(names);
                }

                if(StrUtil.isNotEmpty(record.getSendMsgErrorIds())){
                    String names = getWxUserNames(record.getSendMsgErrorIds());
                    record.setSendMsgErrorNames(names);
                }

                CkTerminal terminal = ckTerminalService.findById(record.getTerminalId());
                if(terminal!=null){
                    record.setTerminalName(terminal.getTerminalName());
                    record.setTerminalNum(terminal.getTerminalNum());
                }
                List<String> imgsList = new ArrayList<>();
                List<TerminalCheckRecordImg> imgs = terminalCheckRecordImgService.selectListByColumn("record_id",record.getId());
                if(imgs!=null){
                    for (TerminalCheckRecordImg img : imgs){
                        imgsList.add(imgUrl + img.getImgUrl());
                    }
                }
                record.setImgsList(imgsList);
            });
        }
        dt = terminalCheckRecordService.pageSearchCustom(page,list,condition);
        return dt;
    }


    @Log("查询设备页面")
    @GetMapping("/info/{terminalId}")
    @RequiresPermissions("module:terminal:terminal")
    String TerminalAllInfo(Model model,@PathVariable("terminalId") Integer terminalId) {
        model.addAttribute("terminalId",terminalId);
        model.addAttribute("isBack",1);

        UserDO userDO = getUser();
        Map<String,Object> map = new HashMap<>();
        if(userDO.getUserType() == 2  || userDO.getUserType() == 13 || userDO.getUserType() == 14){//集团
            map.put("jituan_user_id",userDO.getGroupId());
        } else if(userDO.getUserType() == 3){//片区
            map.put("sys_user_id",userDO.getUserId());
        } else if(userDO.getUserType() == 4 || userDO.getUserType() == 5 || userDO.getUserType() == 6){//片区
            map.put("id",userDO.getShopId());
        }
        List<Shop> list0 = shopService.getPageByUserId(map);
        model.addAttribute("shops", list0);

        CkTerminal terminal = ckTerminalService.findById(terminalId);
        model.addAttribute("terminal", terminal);

        return "module/terminal/terminal_allinfo";
    }


    @Log("查询设备")
    @ResponseBody
    @GetMapping("/info/list")
    @RequiresPermissions("module:terminal:terminal")
    public DataTableLayUI<TerminalCheckRecord> infoList(DataTableLayUI<TerminalCheckRecord> condition) {
        Map<String,Object> map = condition.getSearchParams();
        String terminalNum = map.containsKey("search_eq_terminalNum") ? map.get("search_eq_terminalNum").toString():null;
        String shopId = map.containsKey("search_eq_shopId") ? map.get("search_eq_shopId").toString(): null;
        String tabId = map.containsKey("tab_id") ? map.get("tab_id").toString(): "1";
        String begin_time = map.containsKey("search_ge_createTime") ? map.get("search_ge_createTime").toString():null;
        String end_time = map.containsKey("search_le_createTime") ? map.get("search_le_createTime").toString():null;

        Map<String,Object> map1 = new HashMap<>();
        map1.put("is_clean",0);
        if(StrUtil.isNotEmpty(shopId)){
            map1.put("shop_id",shopId);
        }

        DataTableLayUI<TerminalCheckRecord> dt = null;
        CkTerminal ckTerminal = null;
        if(terminalNum != null && !terminalNum.equals("")){
            ckTerminal = ckTerminalService.selectByUniqueColumn("terminal_num",terminalNum);
            map1.put("terminal_id",ckTerminal.getId());
        }

        if(Integer.parseInt(tabId) == 1) {//巡检记录
            map1.put("is_clean",0);
        } else if(Integer.parseInt(tabId) == 2) {//清理记录
            map1.put("is_clean",1);
        } else if(Integer.parseInt(tabId) == 3) {//保养记录
            map1.put("is_clean",2);
        } else if(Integer.parseInt(tabId) == 4) {//维修记录
            map1.put("check_state",2);
        }
        if(begin_time!=null && end_time!=null){
            map1.put("begin_time",begin_time);
            map1.put("end_time",end_time);
        }
        Page<TerminalCheckRecord> page = terminalCheckRecordService.getPage(condition);
        List<TerminalCheckRecord> list = terminalCheckRecordService.getPageByUserId(page,map1);
        if(list != null){
            list.forEach(record ->{
                Shop shop = shopService.findById(record.getShopId());
                if(shop!=null){
                    record.setShopName(shop.getShopName());
                }
                WxUser wxUser = wxUserService.getById(record.getWxUserId());
                if(wxUser !=null && wxUser.getNickName()!=null){
                    UserDO userDO = userService.findById(wxUser.getSysUserId());
                    if(userDO!=null){
                        record.setUserName(userDO.getName());
                    }
                }

                if(StrUtil.isNotEmpty(record.getSendMsgOkIds())){
                    String names = getWxUserNames(record.getSendMsgOkIds());
                    record.setSendMsgOkIds(names);
                }

                if(StrUtil.isNotEmpty(record.getSendMsgErrorIds())){
                    String names = getWxUserNames(record.getSendMsgErrorIds());
                    record.setSendMsgErrorNames(names);
                }

                CkTerminal terminal = ckTerminalService.findById(record.getTerminalId());
                if(terminal!=null){
                    record.setTerminalName(terminal.getTerminalName());
                    record.setTerminalNum(terminal.getTerminalNum());
                }
                List<String> imgsList = new ArrayList<>();
                List<TerminalCheckRecordImg> imgs = terminalCheckRecordImgService.selectListByColumn("record_id",record.getId());
                if(imgs!=null){
                    for (TerminalCheckRecordImg img : imgs){
                        imgsList.add(imgUrl + img.getImgUrl());
                    }
                }
                record.setImgsList(imgsList);
                QueryWrapper qw = new QueryWrapper();
                qw.eq("record_id",record.getId());
                qw.orderByDesc("repair_time");
                qw.last("limit 1");
                TerminalRecordRepair recordRepair = terminalRecordRepairService.getOne(qw);
                if(recordRepair!=null){
                    record.setRepairName(recordRepair.getRepairName());
                    record.setRepairTime(recordRepair.getRepairTime());
                    record.setRepairState(recordRepair.getRepairState());
                }
            });
        }
        dt = terminalCheckRecordService.pageSearchCustom(page,list,condition);

        return dt;
    }

    private String getWxUserNames(String ids){
        String[] idsArray = ids.split(",");
        String names = "";
        for(String id : idsArray){
            WxUser wxUser1 = wxUserService.getById(id);
            if(wxUser1!=null){
                names += wxUser1.getNickName()+",";
            }
        }
        names = StringUtils.getSplitStr(names);
        return names;
    }

    /**
     * 删除
     */
    @Log("删除处理记录")
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("module:terminal:record:remove")
    public R remove(Integer id) {
        TerminalCheckRecord record = terminalCheckRecordService.findById(id);
        if(record!=null){
            record.setIsDel(1);
            boolean bl = terminalCheckRecordService.updateById(record);
            if(bl){
                return R.ok();
            }
        }
        return R.error("记录不存在");
    }


    @RequiresPermissions("module:terminal:record:batchRemove")
    @Log("批量删除终端")
    @PostMapping("/batchRemove")
    @ResponseBody
    R batchRemove(@RequestParam("ids[]") Integer[] recordIds) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        int count = 0;
        for (Integer id: recordIds){
            TerminalCheckRecord record = terminalCheckRecordService.findById(id);
            if(record != null){
                record.setIsDel(1);
                boolean bl = terminalCheckRecordService.updateById(record);
                if(bl){
                    count++;
                }
            }
        }
        return R.ok("共成功删除" + count + "个");
    }

    @GetMapping("/exportExcel1")
    public void testExprotExcel1(@RequestParam("begin_date") String begin_date,@RequestParam("end_date") String end_date,
                                @RequestParam("is_clean") String is_clean, @RequestParam("shopId") String shopId,
                                @RequestParam("checkState") String checkState, HttpServletRequest request,HttpServletResponse response){
        UserDO user = getUser();
        Map<String,Object> map = new HashMap<>();
        if(user.getUserType() == 0 || user.getUserType() == 1){
            if(StrUtil.isNotEmpty(shopId)){
                map.put("shop_id",Integer.parseInt(shopId));
            }
        } else if(user.getUserType() == 2){//集团管理员
            if(StrUtil.isNotEmpty(shopId)){
                map.put("shop_id",Integer.parseInt(shopId));
            }else{
                map.put("jituan_user_id",user.getUserId());
            }
        }else if(user.getUserType() == 3){//片区管理员
            if(StrUtil.isNotEmpty(shopId)){
                map.put("shop_id",Integer.parseInt(shopId));
            }else{
                map.put("sys_user_id",user.getUserId());
            }
        }
        else if(user.getUserType() == 4 || user.getUserType() == 5 || user.getUserType() == 6){
            map.put("shop_id",user.getShopId());
        }
        if(Integer.parseInt(is_clean) != 2){
            if(StrUtil.isNotEmpty(checkState)){
                map.put("check_state",Integer.parseInt(checkState));
            }
        }

        if(StrUtil.isNotEmpty(begin_date) && StrUtil.isNotEmpty(end_date)){
            map.put("begin_time",begin_date +" 00:00:00");
            map.put("end_time",end_date +" 23:59:59");
        }
        map.put("is_clean",is_clean);
        List<TerminalCheckRecord> records = new ArrayList<>();
        List<TerminalCleanRecord> recordsClean = new ArrayList<>();
        List<TerminalHealthRecord> recordsHealth = new ArrayList<>();
        if(is_clean.equals("0")){
            records = terminalCheckRecordService.getPageByUserId(map);
            records.forEach(record->{
                QueryWrapper<DictDO> qw2 = new QueryWrapper<>();
                qw2.eq("type","check-state");
                qw2.eq("value",record.getCheckState());
                DictDO dictDO2 = dictService.getOne(qw2);
                if(dictDO2 != null) {
                    record.setCheckStateTxt(dictDO2.getName());
                }
                WxUser wxUser = wxUserService.getById(record.getWxUserId());
                if(wxUser !=null && wxUser.getNickName()!=null){
                    UserDO userDO = userService.findById(wxUser.getSysUserId());
                    if(userDO!=null){
                        record.setUserName(userDO.getName());
                    }
                }
                CkTerminal terminal = ckTerminalService.findById(record.getTerminalId());
                if(terminal != null){
                    if(Integer.parseInt(is_clean) == 0){
                        QueryWrapper<DictDO> qw = new QueryWrapper<>();
                        qw.eq("type","clean-cycle-type");
                        qw.eq("value",terminal.getCheckCountUnit());
                        DictDO dictDO = dictService.getOne(qw);
                        if(dictDO != null){
                            record.setCheckCycle(terminal.getCheckCount() + "/" + dictDO.getName());
                        }
                    }else{
                        QueryWrapper<DictDO> qw1 = new QueryWrapper<>();
                        qw1.eq("type","clean-cycle-type");
                        qw1.eq("value",terminal.getCleanCountUnit());
                        DictDO dictDO1 = dictService.getOne(qw1);
                        if(dictDO1 != null){
                            record.setCheckCycle(terminal.getCleanCount() + "/" + dictDO1.getName());
                        }
                    }
                }
            });
        }else if(is_clean.equals("1")){
            recordsClean = terminalCheckRecordService.getCleanPageByUserId(map);
            recordsClean.forEach(record->{
                QueryWrapper<DictDO> qw2 = new QueryWrapper<>();
                qw2.eq("type","check-state");
                qw2.eq("value",record.getCheckState());
                DictDO dictDO2 = dictService.getOne(qw2);
                if(dictDO2 != null) {
                    record.setCheckStateTxt(dictDO2.getName());
                }
                WxUser wxUser = wxUserService.getById(record.getWxUserId());
                if(wxUser !=null && wxUser.getNickName()!=null){
                    UserDO userDO = userService.findById(wxUser.getSysUserId());
                    if(userDO!=null){
                        record.setUserName(userDO.getName());
                    }
                }
                CkTerminal terminal = ckTerminalService.findById(record.getTerminalId());
                if(terminal != null){
                    if(Integer.parseInt(is_clean) == 0){
                        QueryWrapper<DictDO> qw = new QueryWrapper<>();
                        qw.eq("type","clean-cycle-type");
                        qw.eq("value",terminal.getCheckCountUnit());
                        DictDO dictDO = dictService.getOne(qw);
                        if(dictDO != null){
                            record.setCheckCycle(terminal.getCheckCount() + "/" + dictDO.getName());
                        }
                    }else{
                        QueryWrapper<DictDO> qw1 = new QueryWrapper<>();
                        qw1.eq("type","clean-cycle-type");
                        qw1.eq("value",terminal.getCleanCountUnit());
                        DictDO dictDO1 = dictService.getOne(qw1);
                        if(dictDO1 != null){
                            record.setCheckCycle(terminal.getCleanCount() + "/" + dictDO1.getName());
                        }
                    }
                }
            });
        }else if(is_clean.equals("2")){
            recordsHealth = terminalCheckRecordService.getHealthPageByUserId(map);
            recordsHealth.forEach(record->{
                QueryWrapper<DictDO> qw2 = new QueryWrapper<>();
                qw2.eq("type","check-state");
                qw2.eq("value",record.getCheckState());
                DictDO dictDO2 = dictService.getOne(qw2);
                if(dictDO2 != null) {
                    record.setCheckStateTxt(dictDO2.getName());
                }
                WxUser wxUser = wxUserService.getById(record.getWxUserId());
                if(wxUser !=null && wxUser.getNickName()!=null){
                    UserDO userDO = userService.findById(wxUser.getSysUserId());
                    if(userDO!=null){
                        record.setUserName(userDO.getName());
                    }
                }
                TerminalFitting fitting = terminalFittingService.findById(record.getFittingId());
                if(fitting != null){
                    QueryWrapper<DictDO> qw = new QueryWrapper<>();
                    qw.eq("type","clean-cycle-type");
                    qw.eq("value",fitting.getHealthCountUnit());
                    DictDO dictDO = dictService.getOne(qw);
                    if(dictDO != null){
                        record.setHealthCycle("1次/" + fitting.getHealthCount() + dictDO.getName());
                    }
                }
            });
        }

        ExcelUtils<TerminalCheckRecord> util = new ExcelUtils<TerminalCheckRecord>(TerminalCheckRecord.class);
        ExcelUtils<TerminalCleanRecord> utilClean = new ExcelUtils<TerminalCleanRecord>(TerminalCleanRecord.class);
        ExcelUtils<TerminalHealthRecord> utilHealth = new ExcelUtils<TerminalHealthRecord>(TerminalHealthRecord.class);

        String sheetName = "xunjian";
        if(is_clean.equals("1")){
            sheetName = "clean";
        }else if(is_clean.equals("2")){
            sheetName = "baoyang";
        }
        AjaxResult ajaxResult = null;
        if(is_clean.equals("1")){//清洁记录
            ajaxResult = utilClean.exportExcel(recordsClean, sheetName);
        }else if(is_clean.equals("0")){//巡检记录
            ajaxResult = util.exportExcel(records, sheetName);
        }else if(is_clean.equals("2")){//保养记录
            ajaxResult = utilHealth.exportExcel(recordsHealth, sheetName);
        }
        System.out.println("");
        String filename = ajaxResult.get("msg").toString();
        String realFileName = System.currentTimeMillis() + filename.substring(filename.indexOf("_") + 1); //获得系统的时间+获取从第一个“_”位置开始到结束的子字符串
        try
        {
            String filePath = exportPath + filename;
            System.out.println("filePath：" + filePath);
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition","attachment;fileName=" + setFileDownloadHeader(request, realFileName));
            FileUtils.writeBytes(filePath, response.getOutputStream());
//            FileUtils.deleteFile(filePath);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
    }
    @GetMapping("/exportExcel")
    public void testExprotExcel(@RequestParam("begin_date") String begin_date,@RequestParam("end_date") String end_date,
                                @RequestParam("is_clean") String is_clean, @RequestParam("shopId") String shopId,
                                @RequestParam("checkState") String checkState, HttpServletRequest request,HttpServletResponse response){
        UserDO user = getUser();
        Map<String,Object> map = new HashMap<>();
        if(user.getUserType() == 0 || user.getUserType() == 1){
            if(StrUtil.isNotEmpty(shopId)){
                map.put("shop_id",Integer.parseInt(shopId));
            }
        } else if(user.getUserType() == 2){//集团管理员
            if(StrUtil.isNotEmpty(shopId)){
                map.put("shop_id",Integer.parseInt(shopId));
            }else{
                map.put("jituan_user_id",user.getUserId());
            }
        }else if(user.getUserType() == 3){//片区管理员
            if(StrUtil.isNotEmpty(shopId)){
                map.put("shop_id",Integer.parseInt(shopId));
            }else{
                map.put("sys_user_id",user.getUserId());
            }
        }
        else if(user.getUserType() == 4 || user.getUserType() == 5 || user.getUserType() == 6){
            map.put("shop_id",user.getShopId());
        }
        if(Integer.parseInt(is_clean) != 2){
            if(StrUtil.isNotEmpty(checkState)){
                map.put("check_state",Integer.parseInt(checkState));
            }
        }

        if(StrUtil.isNotEmpty(begin_date) && StrUtil.isNotEmpty(end_date)){
            map.put("begin_time",begin_date +" 00:00:00");
            map.put("end_time",end_date +" 23:59:59");
        }
        map.put("is_clean",is_clean);
        List<TerminalCheckRecord> records = new ArrayList<>();
        List<TerminalCleanRecord> recordsClean = new ArrayList<>();
        List<TerminalHealthRecord> recordsHealth = new ArrayList<>();
        if(is_clean.equals("0")){
            records = terminalCheckRecordService.getPageByUserId(map);
            records.forEach(record->{
                QueryWrapper<DictDO> qw2 = new QueryWrapper<>();
                qw2.eq("type","check-state");
                qw2.eq("value",record.getCheckState());
                DictDO dictDO2 = dictService.getOne(qw2);
                if(dictDO2 != null) {
                    record.setCheckStateTxt(dictDO2.getName());
                }
                record.setCreateTimeStr(DateUtils.getTime(record.getCreateTime()));
                WxUser wxUser = wxUserService.getById(record.getWxUserId());
                if(wxUser !=null && wxUser.getNickName()!=null){
                    UserDO userDO = userService.findById(wxUser.getSysUserId());
                    if(userDO!=null){
                        record.setUserName(userDO.getName());
                    }
                }
                CkTerminal terminal = ckTerminalService.findById(record.getTerminalId());
                if(terminal != null){
                    if(Integer.parseInt(is_clean) == 0){
                        QueryWrapper<DictDO> qw = new QueryWrapper<>();
                        qw.eq("type","clean-cycle-type");
                        qw.eq("value",terminal.getCheckCountUnit());
                        DictDO dictDO = dictService.getOne(qw);
                        if(dictDO != null){
                            record.setCheckCycle(terminal.getCheckCount() + "/" + dictDO.getName());
                        }
                    }else{
                        QueryWrapper<DictDO> qw1 = new QueryWrapper<>();
                        qw1.eq("type","clean-cycle-type");
                        qw1.eq("value",terminal.getCleanCountUnit());
                        DictDO dictDO1 = dictService.getOne(qw1);
                        if(dictDO1 != null){
                            record.setCheckCycle(terminal.getCleanCount() + "/" + dictDO1.getName());
                        }
                    }
                }
            });
        }else if(is_clean.equals("1")){
            recordsClean = terminalCheckRecordService.getCleanPageByUserId(map);
            recordsClean.forEach(record->{
                QueryWrapper<DictDO> qw2 = new QueryWrapper<>();
                qw2.eq("type","check-state");
                qw2.eq("value",record.getCheckState());
                DictDO dictDO2 = dictService.getOne(qw2);
                if(dictDO2 != null) {
                    record.setCheckStateTxt(dictDO2.getName());
                }
                WxUser wxUser = wxUserService.getById(record.getWxUserId());
                if(wxUser !=null && wxUser.getNickName()!=null){
                    UserDO userDO = userService.findById(wxUser.getSysUserId());
                    if(userDO!=null){
                        record.setUserName(userDO.getName());
                    }
                }
                CkTerminal terminal = ckTerminalService.findById(record.getTerminalId());
                if(terminal != null){
                    if(Integer.parseInt(is_clean) == 0){
                        QueryWrapper<DictDO> qw = new QueryWrapper<>();
                        qw.eq("type","clean-cycle-type");
                        qw.eq("value",terminal.getCheckCountUnit());
                        DictDO dictDO = dictService.getOne(qw);
                        if(dictDO != null){
                            record.setCheckCycle(terminal.getCheckCount() + "/" + dictDO.getName());
                        }
                    }else{
                        QueryWrapper<DictDO> qw1 = new QueryWrapper<>();
                        qw1.eq("type","clean-cycle-type");
                        qw1.eq("value",terminal.getCleanCountUnit());
                        DictDO dictDO1 = dictService.getOne(qw1);
                        if(dictDO1 != null){
                            record.setCheckCycle(terminal.getCleanCount() + "/" + dictDO1.getName());
                        }
                    }
                }
            });
        }else if(is_clean.equals("2")){
            recordsHealth = terminalCheckRecordService.getHealthPageByUserId(map);
            recordsHealth.forEach(record->{
                QueryWrapper<DictDO> qw2 = new QueryWrapper<>();
                qw2.eq("type","check-state");
                qw2.eq("value",record.getCheckState());
                DictDO dictDO2 = dictService.getOne(qw2);
                if(dictDO2 != null) {
                    record.setCheckStateTxt(dictDO2.getName());
                }
                WxUser wxUser = wxUserService.getById(record.getWxUserId());
                if(wxUser !=null && wxUser.getNickName()!=null){
                    UserDO userDO = userService.findById(wxUser.getSysUserId());
                    if(userDO!=null){
                        record.setUserName(userDO.getName());
                    }
                }
                TerminalFitting fitting = terminalFittingService.findById(record.getFittingId());
                if(fitting != null){
                    QueryWrapper<DictDO> qw = new QueryWrapper<>();
                    qw.eq("type","clean-cycle-type");
                    qw.eq("value",fitting.getHealthCountUnit());
                    DictDO dictDO = dictService.getOne(qw);
                    if(dictDO != null){
                        record.setHealthCycle("1次/" + fitting.getHealthCount() + dictDO.getName());
                    }
                }
            });
        }

        if(is_clean.equals("0")){//巡检记录
            ExcelUtils.writeExcel(response, records, TerminalCheckRecord.class, System.currentTimeMillis() + "_巡检记录.xlsx");
        }else if(is_clean.equals("1")){//清洁记录
            ExcelUtils.writeExcel(response, recordsClean, TerminalCleanRecord.class, System.currentTimeMillis() +"_清洁记录.xlsx");
        }else if(is_clean.equals("2")){//保养记录
            ExcelUtils.writeExcel(response, recordsHealth, TerminalHealthRecord.class, System.currentTimeMillis() +"_保养记录.xlsx");
        }
    }


    public String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException{
        final String agent = request.getHeader("USER-AGENT");
        String filename = fileName;
        if (agent.contains("MSIE"))
        {
            // IE浏览器
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+", " ");
        }
        else if (agent.contains("Firefox"))
        {
            // 火狐浏览器
            filename = new String(fileName.getBytes(), "ISO8859-1");
        }
        else if (agent.contains("Chrome"))
        {
            // google浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        else
        {
            // 其它浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        return filename;
    }
}
